﻿using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;


namespace MessageLib
{
	public static class Statics
	{
		public static string ByteArrayToString(byte[] bytes)
		{
			return string.Join(" ", bytes.Select(i => i.ToString("X2")));
		}



        public static byte[] StringToByteArray(string s)
	    {
	        var _testReg = "([0-9A-F][0-9A-F]\\s*)+";
	        if (!Regex.IsMatch(s, _testReg)) return null;
	        var hex = s.Replace(" ", String.Empty);  
	        return Enumerable.Range(0, hex.Length)
	            .Where(x => x % 2 == 0)
	            .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
	            .ToArray();
        }

        public static byte[] GetEncodingBytes(ControlCommandParam param, string text)
		{
			switch (param)
			{
				case ControlCommandParam.Gbk:
					return Encoding.GetEncoding("GBK").GetBytes(text);
				case ControlCommandParam.Big5:
					return Encoding.GetEncoding("BIG5").GetBytes(text);
				case ControlCommandParam.UnicodeLe:
					return Encoding.Unicode.GetBytes(text);
				case ControlCommandParam.UnicodeBe:
					return Encoding.BigEndianUnicode.GetBytes(text);
				case ControlCommandParam.Gb2312:
				default:
					return Encoding.GetEncoding("GB2312").GetBytes(text);
			}
		}

		public static bool InRange(this int num,int min, int max)
		{
			return num >= min && num < max;
		}

		public static bool IsNumber(this string text, int min, int max)
		{
			int a;
			return int.TryParse(text, out a) && a.InRange(min, max);

		}
	}
}
